package com.example.qt.ptplatform.service.impl;

import com.example.qt.ptplatform.entity.User;
import com.example.qt.ptplatform.entity.UserAssessment;
import com.example.qt.ptplatform.mapper.*;
import com.example.qt.ptplatform.service.UserAssessmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserAssessmentServiceImpl implements UserAssessmentService {
    @Autowired
    private UserAssessmentMapper userAssessmentMapper;
    @Autowired
    private DownloadMapper downloadMapper;
    @Autowired
    private PointRecordMapper pointRecordMapper;
    @Autowired
    private TorrentMapper torrentMapper;
    @Autowired
    private UserMapper userMapper;

    @Scheduled(cron = "0 0 0 ? * SUN")
    public void performMonthlyAssessment() {
        //获取所有用户列表
        List<User> users = userMapper.getAllUsers();

        LocalDate startDate = LocalDate.now().minusMonths(1); // 上月的开始时间
        LocalDate endDate = LocalDate.now().minusDays(1); // 上月的结束时间

        //遍历用户进行考核
        for (User user : users) {
            Double uploadAmountChange = getUploadAmountChange(user.getUserId(), startDate, endDate);
            Double downloadAmountChange = getDownloadAmountChange(user.getUserId(), startDate, endDate);
            Double seedPointsChange = getSeedPointsChange(user.getUserId(), startDate, endDate);
            Double shareRate = calculateShareRate(user.getUserId());

            // 判断考核是否合格
            boolean isPassed = assess(uploadAmountChange, downloadAmountChange, seedPointsChange, shareRate);

            // 保存考核结果
            saveAssessmentResult(user, startDate, endDate, uploadAmountChange, downloadAmountChange, seedPointsChange, shareRate, isPassed);
        }
    }

    // 获取上传量变化
    private Double getUploadAmountChange(Integer userId, LocalDate startDate, LocalDate endDate) {
        // 从torrents表查询用户上传量变化
        // 转换为 LocalDateTime 类型，确保查询的时间范围精确到具体时刻
        LocalDateTime startDateTime = startDate.atStartOfDay();  // 获取当天的00:00
        LocalDateTime endDateTime = endDate.atTime(23, 59, 59); // 获取当天的23:59:59

        // 查询指定时间范围内上传量的总和
        Double uploadAmountChange = torrentMapper.getTotalUploadSizeByUserIdAndTimeRange(userId, startDateTime, endDateTime);

        // 如果上传量为 null，则设为 0.0
        if (uploadAmountChange == null) {
            uploadAmountChange = 0.0;
        }

        // 打印到控制台
        System.out.println("User ID: " + userId + " - Upload amount change from "
                + startDate + " to " + endDate + ": " + uploadAmountChange + " GB");

        return uploadAmountChange;
    }

    // 获取下载量变化
    private Double getDownloadAmountChange(Integer userId, LocalDate startDate, LocalDate endDate) {
        // 从downloads表查询用户下载量变化
        // 转换为 LocalDateTime 类型，确保查询的时间范围精确到具体时刻
        LocalDateTime startDateTime = startDate.atStartOfDay();  // 获取当天的00:00
        LocalDateTime endDateTime = endDate.atTime(23, 59, 59); // 获取当天的23:59:59

        // 查询下载量变化
        Double downloadAmountChange = downloadMapper.getTotalDownloadSizeByUserIdAndTimeRange(userId, startDateTime, endDateTime);

        // 如果下载量为 null，则设为 0.0
        if (downloadAmountChange == null) {
            downloadAmountChange = 0.0;
        }

        // 打印到控制台
        System.out.println("User ID: " + userId + " - Download amount change from "
                + startDate + " to " + endDate + ": " + downloadAmountChange + " GB");

        // 返回下载量变化
        return downloadAmountChange;
    }

    // 获取保种积分变化
    private Double getSeedPointsChange(Integer userId, LocalDate startDate, LocalDate endDate) {
        // 转换为 LocalDateTime 类型，确保查询的时间范围精确到具体时刻
        LocalDateTime startDateTime = startDate.atStartOfDay();  // 获取当天的00:00
        LocalDateTime endDateTime = endDate.atTime(23, 59, 59); // 获取当天的23:59:59

        // 查询保种积分变化
        Double seedPointsChange = pointRecordMapper.getSeedPointsChange(userId, startDateTime, endDateTime);

        // 如果保种积分为 null，则设为 0.0
        if (seedPointsChange == null) {
            seedPointsChange = 0.0;
        }

        // 打印到控制台
        System.out.println("User ID: " + userId + " - Seed points change from "
                + startDate + " to " + endDate + ": " + seedPointsChange + " points");

        // 返回保种积分变化
        return seedPointsChange;
    }

    // 计算分享率
    private Double calculateShareRate(Integer userId) {
        Double shareRate = userMapper.getShareRateByUserId(userId);
        // 如果分享率为 null，则设为 0.0
        if (shareRate == null) {
            shareRate = 0.0;
        }
        // 打印分享率（可选）
        System.out.println("User ID: " + userId + " - Share Rate: " + shareRate);

        return shareRate;
    }

    private boolean assess(Double uploadAmountChange, Double downloadAmountChange, Double seedPointsChange, Double shareRate) {
        // 判断上传量、下载量、保种积分是否增长且分享率 >= 0.1
        if (uploadAmountChange <= 0 || downloadAmountChange <= 0 || seedPointsChange <= 0 || shareRate < 0.1) {
            return false; // 不合格
        }
        return true; // 合格
    }

    private void saveAssessmentResult(User user, LocalDate startDate, LocalDate endDate,
                                      Double uploadAmountChange, Double downloadAmountChange,
                                      Double seedPointsChange, Double shareRate, boolean isPassed) {
        // 保存考核结果
        UserAssessment assessment = new UserAssessment();
        assessment.setUserId(user.getUserId());
        assessment.setAssessmentPeriodStart(startDate);
        assessment.setAssessmentPeriodEnd(endDate);
        assessment.setUploadAmountChange(uploadAmountChange);
        assessment.setDownloadAmountChange(downloadAmountChange);
        assessment.setSeedPointsChange(seedPointsChange);
        assessment.setShareRate(shareRate);
        assessment.setAssessmentStatus(isPassed ? "合格" : "不合格");
        assessment.setAssessmentDate(LocalDate.now());

        userAssessmentMapper.insert(assessment);
    }

    @Override
    public UserAssessment getLatestAssessmentResult(Integer userId) {
        // 查询用户最新的考核结果
        return userAssessmentMapper.selectLatestAssessmentByUserId(userId);
    }

    @Override
    public List<UserAssessment> getAssessmentHistory(Integer userId) {
        // 查询用户的所有考核记录
        return userAssessmentMapper.selectAssessmentHistoryByUserId(userId);
    }
}
